<template>
  <div>
    <!-- AI助手触发按钮 -->
    <div class="ai-assistant-trigger" @click="showDrawer = true">
      <el-button type="primary" circle>
        <el-icon><ChatDotRound /></el-icon>
      </el-button>
    </div>

    <!-- AI聊天抽屉 -->
    <el-drawer
      v-model="showDrawer"
      title="AI 助手"
      direction="rtl"
      size="500px"
      :destroy-on-close="false"
    >
      <div class="ai-chat-container">
        <div class="chat-messages" ref="chatMessages">
          <div v-for="(message, index) in messages" :key="index"
               :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
            <div class="message-content">
              <div class="message-text markdown-body" v-html="formatMessage(message.content)"></div>
              <div class="message-actions">
                <div class="message-time">{{ formatTime(message.timestamp) }}</div>
                <div class="message-buttons">
                  <el-button 
                    v-if="message.role === 'assistant'"
                    type="text" 
                    size="small" 
                    @click="speakMessage(message.content)"
                    :icon="isSpeaking ? 'Mute' : 'VideoPlay'"
                  >
                    {{ isSpeaking ? '停止' : '朗读' }}
                  </el-button>
                  <el-button
                    v-if="message.role === 'assistant'"
                    type="text"
                    size="small"
                    @click="saveToStudyLog(message.content)"
                    icon="DocumentAdd"
                  >
                    保存到学习日志
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          <!-- AI正在回答的提示 -->
          <div v-if="isAiResponding" class="message ai-message">
            <div class="message-content">
              <div class="ai-typing">
                <span class="typing-dot"></span>
                <span class="typing-dot"></span>
                <span class="typing-dot"></span>
                <span class="typing-text">AI正在思考中...</span>
              </div>
            </div>
          </div>
        </div>

        <div class="chat-input">
          <el-input
            v-model="userInput"
            type="textarea"
            :rows="3"
            placeholder="请输入你的问题..."
            @keyup.enter="handleEnter"
            :disabled="isAiResponding"
          />
          <div class="input-actions">
            <el-button 
              type="primary" 
              @click="sendMessage(userInput)" 
              :loading="isAiResponding"
              :disabled="isAiResponding || !userInput.trim()"
            >
              发送
            </el-button>
            <el-button @click="clearChat" :disabled="isAiResponding">
              <el-icon><Delete /></el-icon> 清空对话
            </el-button>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 学习日志抽屉 -->
    <el-drawer
      v-model="showStudyLog"
      title="学习日志"
      direction="rtl"
      size="500px"
      :destroy-on-close="false"
    >
      <StudyLog ref="studyLogRef" />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, onUnmounted } from 'vue'
import { ChatDotRound, Delete, DocumentAdd } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createAgentAi } from "@/uses/agentAi.js"
import StudyLog from './StudyLog.vue'
import { marked } from 'marked'
import 'github-markdown-css/github-markdown.css'

const { ws, sendMessage,agentModel, connected, messages, loading } = createAgentAi();

const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  },
  modelValue: {
    type: Boolean,
    default: false
  },
  initialMessage: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

// AI聊天相关
const showDrawer = ref(props.modelValue)
const userInput = ref('')
const isLoading = ref(false)
const isSpeaking = ref(false)
const chatMessages = ref(null)
let speechSynthesis = null
let currentUtterance = null

const showStudyLog = ref(false)
const studyLogRef = ref(null)

const isAiResponding = ref(false)

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  showDrawer.value = val
})

// 监听showDrawer变化
watch(showDrawer, (val) => {
  emit('update:modelValue', val)
})

// 监听消息变化，自动滚动到底部
watch(() => messages.value, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

// 监听初始消息变化
watch(() => props.initialMessage, (newVal) => {
  if (newVal && showDrawer.value) {
    userInput.value = newVal
    nextTick(() => {
      sendMessage(newVal)
    })
  }
})

// 监听抽屉显示状态
watch(showDrawer, (val) => {
  if (val && props.initialMessage) {
    userInput.value = props.initialMessage
    nextTick(() => {
      sendMessage(props.initialMessage)
    })
  }
})

// 自动滚动到底部
const scrollToBottom = () => {
  if (chatMessages.value) {
    chatMessages.value.scrollTop = chatMessages.value.scrollHeight
  }
}

// 清空对话
const clearChat = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有对话记录吗？', '提示', {
      type: 'warning'
    })
    chatMessages.value = []
  } catch (error) {
    // 用户取消操作
  }
}

// 配置marked选项
marked.setOptions({
  breaks: true,
  gfm: true,
  headerIds: false,
  mangle: false,
  sanitize: false,
  smartLists: true,
  smartypants: true
})

// 格式化消息内容（支持markdown）
const formatMessage = (content) => {
  try {
    return marked(content)
  } catch (error) {
    console.error('Markdown渲染错误:', error)
    return content
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 朗读消息
const speakMessage = (content) => {
  if (isSpeaking.value) {
    // 停止当前朗读
    if (speechSynthesis) {
      speechSynthesis.cancel()
    }
    isSpeaking.value = false
    return
  }

  // 开始新的朗读
  if (!speechSynthesis) {
    speechSynthesis = window.speechSynthesis
  }

  // 创建新的语音实例
  currentUtterance = new SpeechSynthesisUtterance(content)
  currentUtterance.lang = 'zh-CN'
  currentUtterance.rate = 1.0
  currentUtterance.pitch = 1.0

  // 监听朗读结束
  currentUtterance.onend = () => {
    isSpeaking.value = false
  }

  // 开始朗读
  speechSynthesis.speak(currentUtterance)
  isSpeaking.value = true
}

// 保存到学习日志
const saveToStudyLog = (content) => {
  if (studyLogRef.value) {
    const title = content.slice(0, 50) + (content.length > 50 ? '...' : '')
    studyLogRef.value.addLog(title, content)
    ElMessage.success('已保存到学习日志')
  }
}

// 处理回车发送
const handleEnter = (e) => {
  if (e.shiftKey) return // 允许Shift+Enter换行
  if (!isAiResponding.value && userInput.value.trim()) {
    sendMessage(userInput.value)
  }
}

// 发送消息
// 组件卸载时清理
onUnmounted(() => {
  if (speechSynthesis) {
    speechSynthesis.cancel()
  }
})
</script>

<style scoped>
.ai-assistant-trigger {
  position: fixed;
  right: 30px;
  bottom: 30px;
  z-index: 100;
}

.ai-chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.message {
  margin-bottom: 15px;
  display: flex;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 8px;
  position: relative;
}

.user-message .message-content {
  background: #409eff;
  color: #fff;
}

.ai-message .message-content {
  background: #fff;
  border: 1px solid #dcdfe6;
}

.message-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.chat-input {
  margin-top: auto;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.message-buttons {
  display: flex;
  gap: 8px;
}

:deep(.markdown-body) {
  font-size: 14px;
  line-height: 1.6;
}

:deep(.markdown-body pre) {
  background-color: #f6f8fa;
  border-radius: 6px;
  padding: 16px;
  overflow: auto;
}

:deep(.markdown-body code) {
  background-color: rgba(27,31,35,0.05);
  border-radius: 3px;
  font-size: 85%;
  margin: 0;
  padding: 0.2em 0.4em;
}

:deep(.markdown-body pre code) {
  background-color: transparent;
  padding: 0;
}

:deep(.markdown-body table) {
  border-collapse: collapse;
  width: 100%;
  margin: 10px 0;
}

:deep(.markdown-body table th),
:deep(.markdown-body table td) {
  border: 1px solid #dfe2e5;
  padding: 6px 13px;
}

:deep(.markdown-body table tr) {
  background-color: #fff;
  border-top: 1px solid #c6cbd1;
}

:deep(.markdown-body table tr:nth-child(2n)) {
  background-color: #f6f8fa;
}

.user-message :deep(.markdown-body) {
  color: #fff;
}

.user-message :deep(.markdown-body code) {
  background-color: rgba(255,255,255,0.1);
  color: #fff;
}

.user-message :deep(.markdown-body pre) {
  background-color: rgba(255,255,255,0.1);
  color: #fff;
}

.user-message :deep(.markdown-body pre code) {
  color: #fff;
}

.ai-typing {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
}

.typing-dot {
  width: 8px;
  height: 8px;
  background-color: #409eff;
  border-radius: 50%;
  animation: typing 1s infinite ease-in-out;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

.typing-text {
  color: #909399;
  font-size: 14px;
}

@keyframes typing {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}

.el-input.is-disabled :deep(.el-textarea__inner) {
  background-color: #f5f7fa;
  cursor: not-allowed;
}
</style>
